package com.authine.cloudpivot.web.api.secondopen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.secondopen.dao.Iusi6cgbMapper;
import com.authine.cloudpivot.web.api.secondopen.domain.IdList;
import com.authine.cloudpivot.web.api.secondopen.domain.Iusi6cgb;
import com.authine.cloudpivot.web.api.secondopen.modules.*;
import com.authine.cloudpivot.web.api.secondopen.service.PurManagementService;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PurManagenmentServiceImpl implements PurManagementService {
    private static final Logger log = LoggerFactory.getLogger(PurManagenmentServiceImpl.class);


    @Autowired
    private Iusi6cgbMapper iusi6cgbMapper;

    @Autowired
    private HxConfig hxConfig;



    @Override
    public List<Iusi6cgb> queryPurchaseOrder(String supplier, String stime, String etime, String sqlx) {
        return iusi6cgbMapper.queryPurchaseOrder(supplier,stime,etime,sqlx);
    }


    @Override
    public int creacreateItemNumber(IdList idList) {
        return iusi6cgbMapper.creacreateItemNumber(idList);

    }

    @Override
    public int updatecgbStatus(List list,String tableName,String status) {
        if ("零修件".equals(tableName)){
            //修改零修铆焊申请子表状态
            return iusi6cgbMapper.updatecgbStatus(list,status);
        }else if("零星维修工程".equals(tableName)){
            //修改零修维修工程子表状态
            return iusi6cgbMapper.updatelxwxgcStatus(list,status);
        }else{
            //修改零星服务申请单状态
            return  iusi6cgbMapper.updatelxfwStatus(list,status);
        }
    }

    @Override
    public int updateRequisitionsStatus(IdList idList,String tableName) {
        return iusi6cgbMapper.updateRequisitionsStatus(idList,tableName);
    }

    @Override
    public List<QADMdmLdWipDetVO> getStock(String queryType, String queryLot) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmLdWipDetGet";
        String xtoken = hxConfig.getToken();

        url=url+"MdmLdWipDet/Get"+"?queryType="+queryType+"&"+"queryLot="+queryLot;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, xcode, xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<QADMdmLdWipDetVO> qadMdmLdWipDetVOS = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {

            JSONArray data = jsonObject.getJSONArray("data");
            System.out.println(1);
            log.info("--------列表接口返回:data={}",data);
            System.out.println(1);
            if (!CollectionUtils.isEmpty(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    //设置id
                    //qadMdmLdWipDetVO.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    QADMdmLdWipDetVO qadMdmLdWipDetVO = new QADMdmLdWipDetVO();
                    qadMdmLdWipDetVO.setId(object.getString("MdmLdWipPart"));
                    //获取零件号
                    qadMdmLdWipDetVO.setPart(object.getString("MdmLdWipPart"));
                    //获取品名
                    qadMdmLdWipDetVO.setPm(object.getString("MdmLdWipDesc1"));
                    //获取规格
                    qadMdmLdWipDetVO.setGg(object.getString("MdmLdWipDesc2"));
                    //获取地点
                    qadMdmLdWipDetVO.setDd(object.getString("MdmLdWipSite"));
                    //获取库位
                    qadMdmLdWipDetVO.setKw(object.getString("MdmLdWipLoc"));
                    //获取批次
                    qadMdmLdWipDetVO.setPc(object.getString("MdmLdWipLot"));
                    //获取可用数量
                    qadMdmLdWipDetVO.setKysl(object.getBigDecimal("MdmLdWipQty"));
                    //获取工序
                    qadMdmLdWipDetVO.setGx(object.getString("MdmLdWipOp"));
                    //获取工序描述
                    qadMdmLdWipDetVO.setGxms(object.getString("MdmLdWipOpStd"));
                    //获取参考号
                    qadMdmLdWipDetVO.setCkh(object.getString("MdmLdWipRef"));
                    //获取货格
                    qadMdmLdWipDetVO.setHg(object.getString("MdmLdWipGrid"));
                    qadMdmLdWipDetVOS.add(qadMdmLdWipDetVO);
                }
            }
        }
        return  qadMdmLdWipDetVOS;
    }


    @Override
    public QadResultVO sendinvoice(QadInvoiceDTO qadInvoiceVO) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmCInvoicePost";
        String xtoken = hxConfig.getToken();
        url=url+"MdmCInvoice/Post";
        QadInvoiceDTO qvo = setQADFPParams(qadInvoiceVO);
        String s =JSON.toJSONString(qvo);
        String result =HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,s);
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO=new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;
    }

    /**
     * 封装qad供应商发票对象
     * @param qvo
     * @return
     */
    public QadInvoiceDTO setQADFPParams(QadInvoiceDTO qvo){
        String s="SystemDefault";
        //发票状态代码
        String reasoncode="sup-ini";
        //描述
        qvo.setMdmIcCInvoiceDescription(s);
        //日记账集代码
        qvo.setMdmIcCInvoiceDayBookSetCode(s);
        //地点
        qvo.setMdmIcCInvoiceSiteCode(s);
        //日记账代码
        qvo.setMdmIcJournalCode(s);
        //应税
        qvo.setMdmIlCInvoiceIsTaxable(true);
        //不含税
        qvo.setMdmIlCInvoiceIsTaxExcluded(true);
        //分账户 MdmIcDivisionCode
        qvo.setMdmIcDivisionCode(s);
        //成本中心
        qvo.setMdmIcCostCentreCode(s);
        //项目
        qvo.setMdmIcProjectCode(s);
        //业务关系代码
        qvo.setMdmIcShipToBusinessRelation(s);
        //链接到发票
        qvo.setMdmIiLinkedPeriodYear(0);
        //链接到发票第二个字段
        qvo.setMdmIcLinkedJournalCode(s);
        //凭证
        qvo.setMdmIiLinkedCInvoiceVoucher(0);
        return qvo;
    }

    @Override
    public List<SporadicServicesVO> querylxfwPurchaseOrder(PurchaseOrderDTO orderDTO) {
        return iusi6cgbMapper.querylxfwPurchaseOrder(orderDTO);
    }

    @Override
    public QadResultVO sendPopoMt(LMDTO evo) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmPopoMtPost";
        String xtoken = hxConfig.getToken();

        QADExpenseOrderVO qadExpenseOrderVO = new QADExpenseOrderVO();
        //采购订单
        qadExpenseOrderVO.setMdmPoNbr(evo.getDdh());
        //供应商
        qadExpenseOrderVO.setMdmPoVend(evo.getGys());
        //发货至
        qadExpenseOrderVO.setMdmPoShip(evo.getFhz());
        //订单日期
        qadExpenseOrderVO.setMdmPoOrdDate(evo.getDdrq());
        //截止日期
        qadExpenseOrderVO.setMdmPoDueDate(evo.getJzrq());
        //票据开往
        qadExpenseOrderVO.setMdmPoBill(evo.getPjkw());
        //折扣表
        qadExpenseOrderVO.setMdmPoPrList2(evo.getGys());
        //汇总子表方法
        List<LMVO> lmvos = DdDataSummary(evo.getLm());
        List<QADMdmPodDetVO> mdmPodDet = qadExpenseOrderVO.getMdmPodDet();

        for (int i = 0; i < lmvos.size(); i++) {
            LMVO lmvo = lmvos.get(i);
            QADMdmPodDetVO qvo=new QADMdmPodDetVO();
            //行
            qvo.setMdmPodetLine(i+1);
            //零件号
            String s=lmvo.getMc();
            String newpart=null;
            if (s.length()>18){
                newpart=s.substring(0,18)+"=";
            }
            qvo.setMdmPodetPart(newpart+"=");
            //数量
            qvo.setMdmPodetQtyOrd(1);
            //单位
            qvo.setMdmPodetUm("批");
            //单位成本
            qvo.setMdmPodetPurCost(lmvo.getJe());
            //主账户
            //qvo.setMdmPodetAcct(lmvo.getZh());
            //分账户
            //qvo.setMdmPodetSub(lmvo.getFzh());
            //成本中心
            //qvo.setMdmPodetCc(lmvo.getCbzx());
            //项目
            //qvo.setMdmPodetProj(lmvo.getXm());

            mdmPodDet.add(qvo);
        }
        qadExpenseOrderVO.setMdmPodDet(mdmPodDet);
        url=url+"MdmPopoMt/Post";
        String s ="["+ JSON.toJSONString(qadExpenseOrderVO)+"]";
        String result =HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,s);
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO=new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;
    }

    /**
     * 费用订单数据处理
     */
    public List<LMVO> DdDataSummary(List<LMVO> lm){
        List<LMVO> ll=new ArrayList<>();
        //根据账户、分账户、成本中心进行分组
        lm.parallelStream().collect(Collectors.groupingBy(d ->d.getCbzx() +d.getFzh() +d.getZh()+d.getGys(),Collectors.toList()))
                .forEach((id,groupList)->{
                    groupList.stream().reduce(
                            (a,b)-> new LMVO(a.getMc(),
                                    a.getCbzx(),
                                    a.getZh(),
                                    a.getFzh(),
                                    a.getJe(),
                                    b.getJe()))
                            .ifPresent(ll::add);
                });
        return ll;
    }

    @Override
    public QadResultVO sendScrap(QADScrapOrderDTO qadScrapOrderDTO) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmScrapOrderPost";
        String xtoken = hxConfig.getToken();
        url=url+"MdmScrapOrder/Post";
        String  s=JSON.toJSONString(qadScrapOrderDTO);
        String result =HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,s);
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO=new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONObject data1 = jsonObject.getJSONObject("data");
            //JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data1);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;
    }

    @Override
    public List<ScrapVO> getOutPlanRsn() {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmOutPlanRsnGet";
        String xtoken = hxConfig.getToken();
        url=url+"MdmOutPlanRsn/Get";
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, xcode, xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<ScrapVO> scrapVOS=new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    ScrapVO scrapVO = new ScrapVO();
                    JSONObject object = (JSONObject) data.get(i);
                    //原因描述
                    String mdmScrapCodeDesc = object.getString("MdmOutPlanRsnDesc");
                    scrapVO.setId(mdmScrapCodeDesc);
                    scrapVO.setMdmScrapCodeDesc(mdmScrapCodeDesc);
                    scrapVOS.add(scrapVO);
                }
            }
        }
        return scrapVOS;
    }

    @Override
    public List<ScrapVO> getScrapCode(String desc) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmScrapCodeGet";
        String xtoken = hxConfig.getToken();
        url=url+"MdmScrapCode/Get"+"?codeFrom=&codeTo=&codeDesc=";
        if (StringUtils.isNotBlank(desc)){
            url=url+desc;
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, xcode, xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<ScrapVO> scrapVOS=new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    ScrapVO scrapVO = new ScrapVO();
                    JSONObject object = (JSONObject) data.get(i);
                    //原因代码
                    String mdmScrapCodeCode = object.getString("MdmScrapCodeCode");
                    //原因描述
                    String mdmScrapCodeDesc = object.getString("MdmScrapCodeDesc");
                    scrapVO.setId(mdmScrapCodeCode);
                    scrapVO.setMdmScrapCodeCode(mdmScrapCodeCode);
                    scrapVO.setMdmScrapCodeDesc(mdmScrapCodeDesc);
                    scrapVOS.add(scrapVO);
                }
            }
        }
        return scrapVOS;
    }

    @Override
    public List<LxwxgcdVO> querylxwxgc(String gys) {
        List<LxwxgcdVO> querylxwxgc = iusi6cgbMapper.querylxwxgc(gys);
        List<LxwxgcdVO> list =new ArrayList<>();
        for (int i = 0; i < querylxwxgc.size(); i++) {
            LxwxgcdVO lxwxgcdVO = querylxwxgc.get(i);
            //获取部门id
            String gsbm = lxwxgcdVO.getGsbm().substring(8,40);;
            //根据部门id查询部门名称
            String s = iusi6cgbMapper.querybmmcById(gsbm);
            lxwxgcdVO.setGsbm(s);
            list.add(lxwxgcdVO);
        }
        return list;
    }

    @Override
    public List<LxfwdVo> querylxfwsq(String gys) {
        List<LxfwdVo> querylxfwsq = iusi6cgbMapper.querylxfwsq(gys);
        List<LxfwdVo> list = new ArrayList<>();
        for (int i = 0; i < querylxfwsq.size(); i++) {
            LxfwdVo lxfwdVo = querylxfwsq.get(i);
            //获取部门id
            String gsbm = lxfwdVo.getJrbm().substring(8,40);;
            //根据部门id查询部门名称
            String s = iusi6cgbMapper.querybmmcById(gsbm);
            lxfwdVo.setJrbm(s);
            list.add(lxfwdVo);
        }
        return list;
    }

    @Override
    public QadResultVO sendPopoMt2(QADExpenseOrderVO qadExpenseOrderVO) {
        String url = hxConfig.getQadurlheader();
        String xdomain =hxConfig.getXdomain();
        String xcode="MdmPopoMtPost";
        String xtoken = hxConfig.getToken();
        url=url+"MdmPopoMt/Post";
        String s ="["+ JSON.toJSONString(qadExpenseOrderVO)+"]";
        String result =HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url,"",xdomain,xcode,xtoken,s);
        log.info("------------------------"+JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO=new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code=jsonObject.getString("code");
            String msg=jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            qadResultVO.setCode(code);
            if ("10001".equals(code)){
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);
                    msg =(String) jsonObject1.get("errormessage");
                }
            }
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(qadResultVO));
        }
        return qadResultVO;
    }

    @Override
    public String getJobNumberById(String id) {
          return iusi6cgbMapper.getJobNumberById(id);
    }

    @Override
    public String getMesByJobNumber(String id) {
        return iusi6cgbMapper.getMesByJobNumber(id);
    }
}
